import {Image, View} from "@tarojs/components";
import {Component} from "react";
import {createClassFun, CUSTOM_SCHOOL_LOGO_IDS} from "../utils";
import loginBackGroundImage from "../images/login-back.png"
import "./index.scss"
import {InputComponent} from "../inputComponent";
import loginSchoolIcon from "../images/login-school-icon.png"
import loginUserIcon from "../images/login-user.png"
import loginPasswordIcon from "../images/login-password.png"
import LgButton from "../../components/button";
import Taro from "@tarojs/taro"
import {LoginResult, LoginResultState, OnShowAppParams, SchoolSimpleInfo} from "../types";
import {getSchoolSimpleInfoList, loginByUserNameAndPassword} from "../api";
import {Toast} from "../toast";
import {md5Utils} from "../md5";
import {getStorage} from "../../components/utils";
import LgCheckbox from "../../components/checkbox";
import {AgreementPop, usePopLayer} from "../popLayer";


const storage = getStorage();

const {classNames, rootClass} = createClassFun("weapp-login-component")

export interface LoginComponentProps {
  appId: string
  loginIcon: string
  systemName: string
  systemId: string
  showRegisterBtn?: boolean
  showForgetPassword?: boolean
  showVisitorBtn?: boolean
  registerPath?: string

  onLoginSuccess?(loginResult: LoginResult): void
}

export interface LoginComponentState {
  lockSchoolChosen: boolean
  currentSchoolId: string
  currentSchoolVersion: string
  currentSchoolItem: SchoolSimpleInfo | object
  searchSchoolName: string
  userName: string
  password: string
  schoolShowList: SchoolSimpleInfo[]
  isAgreement: number
  popVisible:boolean
}

export class LoginComponent extends Component<LoginComponentProps, LoginComponentState> {

  private currentSchoolId: string
  private schoolList: SchoolSimpleInfo[]

  constructor(props) {
    super(props);
    this.currentSchoolId = ""
    this.schoolList = []
    this.state = {
      lockSchoolChosen: false,
      currentSchoolId: '',
      currentSchoolVersion: '2.0',
      currentSchoolItem: {},
      searchSchoolName: "",
      userName: "",
      password: "",
      schoolShowList: [],
      isAgreement: 0,
      popVisible:false,
    }
  }

  async loadSchoolInfo() {
    try {
      const schoolSimpleInfos = await getSchoolSimpleInfoList();
      let currentSchoolInfo: any = storage.get("currentSchoolInfo")
      currentSchoolInfo = currentSchoolInfo ? JSON.parse(currentSchoolInfo) : ''
      let searchSchoolName = this.state.searchSchoolName;
      let currentSchoolId = this.state.currentSchoolId
      let currentSchoolVersion = this.state.currentSchoolVersion
      let currentSchoolItem = this.state.currentSchoolItem
      if (currentSchoolInfo) {
        this.currentSchoolId = currentSchoolInfo.schoolId
        currentSchoolId = currentSchoolInfo.schoolId
        currentSchoolVersion = currentSchoolInfo.version
        currentSchoolItem = currentSchoolInfo
        searchSchoolName = currentSchoolInfo.schoolName
      }
      this.schoolList = schoolSimpleInfos
      this.setState({
        currentSchoolId,
        currentSchoolVersion,
        currentSchoolItem,
        searchSchoolName,
      })
    } catch {
      Toast.error("获取学校数据失败")
    }
  }

  checkLockSchoolChosen(): boolean {//扫码 || 非退出情况下重新登录 || lockId
    const currentSchoolInfo = JSON.parse(storage.get('currentIdentityInfo') || '{}')
    const app = Taro.getApp().$app
    const schoolId = currentSchoolInfo.schoolID// S-XHWLXX
    const isLogOut = app.isUserLogout
    return !isLogOut && !!CUSTOM_SCHOOL_LOGO_IDS.find(item => item === schoolId)
  }

  async checkIsLockSchoolChoose() {
    const app = Taro.getApp().$app
    if (app.isUserLogout) {
      this.setState({lockSchoolChosen: false})
    } else {
      const onShowOptionsSync = await Taro.getEnterOptionsSync()//报错但能正常使用
      const store: any = JSON.parse(storage.get('onShowOptionsSyncInfo') || '{}')
      let query = onShowOptionsSync.query || store.query as OnShowAppParams// {"lockSchoolId":"S-XHWLXX"} 优先级扫码>缓存

      const lockSchoolId = query.lockSchoolId || ''
      const schoolList = this.schoolList
      let currentSchoolInfo
      if (lockSchoolId) {
        currentSchoolInfo = schoolList.find(item => item.schoolId === lockSchoolId) as SchoolSimpleInfo
      } else {
        currentSchoolInfo = JSON.parse(storage.get('currentIdentityInfo') || '{}')
      }
      const lockSchoolChosen = lockSchoolId || this.checkLockSchoolChosen()
      if (lockSchoolChosen) {
        this.setState({lockSchoolChosen: lockSchoolChosen, currentSchoolItem: currentSchoolInfo})
        this.selectSchool(lockSchoolId, currentSchoolInfo)
      }
    }
  }

  async componentDidMount() {
    await this.loadSchoolInfo()
    await this.checkIsLockSchoolChoose()
    this.updateAgreementState()
  }

  updateAgreementState() {
    const storeAgreement = parseInt(storage.get('isAgreement') || '0')
    this.setState({isAgreement: storeAgreement})
    const refDom:any = this.refs.agreementRef
    refDom.setVal(storeAgreement)
  }

  updateSchoolShowList() {
    this.currentSchoolId = ""
    if (this.state.searchSchoolName) {
      this.setState({
        schoolShowList: this.schoolList.filter(item => {
          const schoolName = item.schoolName
          if (this.state.searchSchoolName.indexOf('LG') != -1) {//包含LG
            return schoolName.indexOf('LG') != -1 && schoolName.indexOf(this.state.searchSchoolName) != -1
          } else {
            return schoolName.indexOf('LG') == -1 && schoolName.indexOf(this.state.searchSchoolName) != -1
          }
        })
      })
    } else if (this.state.schoolShowList.length) {
      this.setState({
        schoolShowList: []
      })
    }
  }

  triggerPrivate(value) {
    this.setState({ isAgreement:value })
  }

  navToPrivacy() {
    Taro.navigateTo({url: "/pages/agreement/index"})
  }


  confirmAgreement(){
    this.setState({ popVisible:false, isAgreement:1 })
    const refDom:any = this.refs.agreementRef
    refDom.setVal(1)
  }
  closePop(){
    this.setState({ popVisible:false })
  }

  render() {
    const currentSchoolItem = this.state.currentSchoolItem as SchoolSimpleInfo
    const lockSchoolChosen = this.state.lockSchoolChosen
    const schoolLogo = lockSchoolChosen ? (currentSchoolItem.schoolLogoUrl || this.props.loginIcon) : this.props.loginIcon
    const schoolName = lockSchoolChosen ? currentSchoolItem.schoolName : this.props.systemName

    return (
      <View className={rootClass("")}>
        <View className={classNames("header")}>
          <Image mode="aspectFill" src={loginBackGroundImage} className={classNames("background")}/>
          <View className={classNames("info")}>
            <Image mode="aspectFill" src={schoolLogo} className={classNames("login-icon")}/>
            <View className={classNames("system-name")}>{schoolName}</View>
          </View>
        </View>
        <View className={classNames("body")}>
          <View className={classNames("form")}>
            <View className={classNames("input-item")}>
              {
                lockSchoolChosen ? null : (
                  <InputComponent onFocus={() => this.searchInputFocus()}
                                  onInput={value => this.setState({
                                    searchSchoolName: value,
                                    currentSchoolId: ''
                                  }, () => this.updateSchoolShowList())}
                                  className={classNames("school-search-input")} value={this.state.searchSchoolName}
                                  icon={loginSchoolIcon} placeholder="请输入名称搜索学校...">
                    {
                      !this.state.schoolShowList.length ? "" :
                        <View className={classNames("school-list")}>
                          {
                            this.state.schoolShowList.map(item => (
                              <View onClick={() => this.selectSchool(item.schoolId, item)}
                                    key={item.id}
                                    className={classNames("school-list-item")}>
                                {
                                  item.schoolName
                                }
                              </View>
                            ))
                          }
                        </View>
                    }
                  </InputComponent>
                )
              }
              <InputComponent value={this.state.userName} onInput={value => this.setState({userName: value})}
                              icon={loginUserIcon} placeholder="请输入帐号..."/>
              <InputComponent password={true} value={this.state.password}
                              onInput={value => this.setState({password: value})} icon={loginPasswordIcon}
                              placeholder="请输入密码..."/>
            </View>
            <View className={(classNames("private"))}>
              <LgCheckbox ref={"agreementRef"} type='B' default={this.state.isAgreement} onClick={this.triggerPrivate.bind(this)}/>
              <View className={(classNames("private-text"))}>
                我已阅读并同意
                <View className={(classNames("private-text-point"))} onClick={this.navToPrivacy.bind(this)}>
                  《用户服务协议》
                </View>
                及
                <View className={(classNames("private-text-point"))} onClick={this.navToPrivacy.bind(this)}>
                  《隐私保护协议》
                </View>
              </View>
            </View>
            <View className={classNames("btn-area")}>
              <LgButton onClick={() => this.login()} type="B" className={classNames("login-btn")}>登录</LgButton>
            </View>
            {
              this.state.currentSchoolId && this.state.currentSchoolVersion !== '1.0' ? (
                <View className={classNames("hand-area")}>
                  {
                    this.props.showForgetPassword ? (
                      <View className={(classNames("hand-area-item"))} onClick={() => {
                        this.goToForgetPwd()
                      }}>忘记密码？</View>
                    ) : null
                  }
                  {/*{*/}
                  {/*  this.props.showVisitorBtn ? (*/}
                  {/*    <View className={(classNames("hand-area-item"))} onClick={() => {*/}
                  {/*      this.goToVisitor()*/}
                  {/*    }}>游客访问</View>*/}
                  {/*  ) : null*/}
                  {/*}*/}
                </View>
              ) : null
            }
          </View>
        </View>
        <View className={classNames("footer")}>
          {
            this.props.showRegisterBtn && this.state.currentSchoolId && this.state.currentSchoolVersion !== '1.0' ?
              <View className={classNames("register-tips")}>
                还没有帐号？点击<View onClick={() => this.gotoRegister()}
                              className={classNames("register-btn")}>注册帐号</View>
              </View> : null
          }
        </View>

        <AgreementPop visible={this.state.popVisible} onConfirm={this.confirmAgreement.bind(this)} onClose={this.closePop.bind(this)}/>
      </View>
    )
  }

  private gotoRegister() {
    if (!this.props.registerPath) {
      return
    }
    Taro.navigateTo({
      url: this.props.registerPath
    }).then()
  }

  private goToForgetPwd() {
    Taro.navigateTo({
      url: '/pages/forgetPassword/index'
    }).then()
  }

  private selectSchool(schoolId: string, item: SchoolSimpleInfo) {
    this.currentSchoolId = schoolId
    storage.set('currentSchoolInfo', JSON.stringify(item))
    this.setState({
      currentSchoolId: schoolId,
      currentSchoolVersion: item.version,
      currentSchoolItem: item,
      searchSchoolName: item.schoolName,
      schoolShowList: []
    })
  }

  private async login() {
    const searchSchoolName = this.state.searchSchoolName.trim();
    if (!searchSchoolName) {
      Toast.error("请输入学校名称")
      return
    }

    let currentSchoolId = this.currentSchoolId;
    if (!currentSchoolId) {
      const schoolInfo = this.schoolList.find(item => item.schoolName === this.state.searchSchoolName)
      if (!schoolInfo) {
        Toast.error("该学校不存在")
        return
      }
      currentSchoolId = schoolInfo.schoolId
    }

    const userName = this.state.userName.trim();
    if (!userName) {
      Toast.error("请输入帐号")
      return
    }

    const password = this.state.password.trim();
    if (!password) {
      Toast.error("请输入密码")
      return
    }

    const isAgreement = this.state.isAgreement
    if(!isAgreement){
      this.setState({ popVisible:true })
      return
    }

    try {
      Toast.showLoading("请稍后")
      const successCallbackResult = await Taro.login();
      const loginResult = await loginByUserNameAndPassword({
        AppID: this.props.appId,
        PSW: md5Utils.reverseMD5String(password),
        SchoolID: currentSchoolId,
        SysTemID: this.props.systemId,
        UserID: userName,
        js_Code: successCallbackResult.code
      });
      Toast.hideLoading()
      switch (loginResult.state) {
        case LoginResultState.SUCCESS:
          this.props.onLoginSuccess && this.props.onLoginSuccess(loginResult);
          break;
        case LoginResultState.UNBIND:
          break;
        case LoginResultState.LOGIN_YUN_FAIL:
          await Toast.error(loginResult.msg || "登录失败，请稍候再试");
          break;
        case LoginResultState.LOGIN_WX_FAIL:
          break;////获取微信信息失败，一般是获取UinonID失败
        case LoginResultState.LOGIN_ERROR_SCHOOL_ID:
          await Toast.error('获取学校信息失败,请重新登录');
          break;
        case LoginResultState.OTHER_FAIL:
          await Toast.error("登录失败，请稍候再试");
          break;
      }
    } catch (e) {
      Toast.hideLoading()
      Toast.error(e instanceof Error && e.message ? e.message : "登录失败")
    }
  }

  private searchInputFocus() {
    this.updateSchoolShowList()
  }
}
